package com.strato.mvc.menu.v1_0_0.handler;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.osgi.framework.Bundle;

import com.strato.annotation.base.v1_0_0.handler.AbstractAnnotationHandler;
import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.annotation.osgi.v1_0_0.service.OsgiWired;
import com.strato.base.env.v1_0_0.GlobalEnvironment;
import com.strato.mvc.annotation.v1_0_0.annotation.method.RequestMapping;
import com.strato.mvc.menu.v1_0_0.Menu;
import com.strato.mvc.menu.v1_0_0.MenuStore;
import com.strato.mvc.menu.v1_0_0.annotation.MenuItem;

@OsgiService
public class MenuAnnotationHandler extends AbstractAnnotationHandler{

	@OsgiWired
	private MenuStore menuStore;
	
	@Override
	public void handleMethod(Bundle bundle, Method method, Class<?> clazz, Annotation annotation) {
		if (!MenuItem.class.equals(annotation.annotationType())) {
			return;
		}
		MenuItem mi=method.getAnnotation(MenuItem.class);
		String path=mi.path();
		String text=mi.text();
		String url=mi.url();
		String icon=mi.icon();
		String group=mi.group();
		boolean includeContext=mi.includeContext();
		if(MenuItem.AUTO_DETECT_URL.equals(url)){
			RequestMapping rm = method.getAnnotation(RequestMapping.class);
			if(rm==null){
				System.out.println("Ignore menu item '"+path+"' because no @RequestMapping is annotated");
				return;
			}
			com.strato.mvc.annotation.v1_0_0.annotation.type.RequestMapping trm=clazz.getAnnotation(com.strato.mvc.annotation.v1_0_0.annotation.type.RequestMapping.class);
			String rmValue=GlobalEnvironment.getInstance().resolveString(rm.value());
			if(trm==null){
				url=rmValue;
			}else{
				String trmValue=GlobalEnvironment.getInstance().resolveString(trm.value());
				url=trmValue+rmValue;
			}
			includeContext=false;
		}
		Menu menu=new Menu();
		menu.setIncludeContext(includeContext);
		menu.setPath(path);
		menu.setText(text);
		menu.setIcon(icon);
		menu.setUrl(url);
		menu.setOrder(mi.order());
		menuStore.store(group,path, menu);
	}

}
